package com.sgd;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * ExecutorService
 *
 * Executors 静态类封装了 ThreadPoolExecutor
 * ExecutorService 是 ThreadPoolExecutor 的接口
 */
public class ExecutorServiceDemo {
    public static void main(String[] args) {
        // 创建一个单线程的线程池
        // ExecutorService executorService = Executors.newSingleThreadExecutor();
        // 创建一个固定大小的线程池（这里线程数量是几，就会启动几个线程: 核心线程数=最大线程数=nThreads）
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        // 提交多个任务到线程池中执行
        for (int i = 0; i < 100; i++) {
            executorService.submit(new RunnableTask(i));
        }

        // 关闭线程池
        executorService.shutdown();
    }
}

/**
 * 多线程要执行的任务
 */
class RunnableTask implements Runnable {
    private int taskId;

    public RunnableTask(int taskId) {
        this.taskId = taskId;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在操作任务" + taskId);

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "已完成任务" + taskId);
    }
}